package com.reider.log4AS3.utils
{
	import com.reider.log4AS3.event.LocalEvent;
	
	import flash.events.EventDispatcher;
	import flash.events.StatusEvent;
	import flash.net.LocalConnection;
	
	public class LocalConnecter extends EventDispatcher
	{
		
		private var recieveConn:LocalConnection
		private var sendConn:LocalConnection
		private var localConnName:String;
		private var remoteConnName:String;
		private var connected:Boolean = false;
		
		public function LocalConnecter(localConnName:String, remoteConnName:String, target:Object)
		{
			this.localConnName = localConnName;
			this.remoteConnName = remoteConnName;
			
			recieveConn = new LocalConnection();
			recieveConn.client = new ScopeManagger(this, target, ["_recievePing"])
			recieveConn.allowDomain("*")
			
			sendConn = new LocalConnection();
			sendConn.addEventListener(StatusEvent.STATUS,sendStatus)
		}
		
		public function connect():void
		{
			recieveConn.connect(localConnName);
			pingReciever()
		}
		
		private function pingReciever():void
		{
			sendConn.send(remoteConnName,"_recievePing")
		}
		
		public function _recievePing():void
		{
			if(!connected){
				sendConn.send(remoteConnName,"_recievePing")
				connected = true;
				dispatchEvent(new LocalEvent(LocalEvent.CONNECT));
			}
		}
		
		public function callFunction(func:String, ... args):void
		{
			if(connected){
				args.unshift(func)
				args.unshift(remoteConnName)
				sendConn.send.apply(null,args)
			}else{
				trace("Not Connected");
			}
		}
		
		private function sendStatus(event:StatusEvent):void{
			dispatchEvent(new LocalEvent(LocalEvent.STATUS,event))
		}
	}
}